package com.suncky.frame.base.mvvm;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelStoreOwner;

import com.suncky.frame.base.BaseDataBindingFragment;

import java.lang.reflect.ParameterizedType;

public abstract class BaseMvvmFragment<B extends ViewDataBinding, VM extends BaseViewModel> extends BaseDataBindingFragment<B> {

    private VM viewModel;

    public VM getViewModel() {
        return viewModel;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        initViewModel();
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    private void initViewModel() {
        viewModel = createViewModel();
        if (viewModel != null) {
            viewModel.getLoadState().observe(getViewLifecycleOwner(), new Observer<LoadState>() {
                @Override
                public void onChanged(LoadState loadState) {
                    onLoadStateChang(loadState);
                }
            });
        }
    }

    @SuppressWarnings("unchecked")
    protected VM createViewModel() {
        try {
            // 获取当前对象的泛型的父类类型
            ParameterizedType pt = (ParameterizedType) (this.getClass().getGenericSuperclass());
            // 获取第二个类型参数的真实类型
            Class<VM> pClass = (Class<VM>) pt.getActualTypeArguments()[1];
            return new ViewModelProvider(getViewModelStoreOwner()).get(pClass);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    protected ViewModelStoreOwner getViewModelStoreOwner() {
        return this;
    }

    private void onLoadStateChang(LoadState loadState) {
        if (loadState == null) {
            return;
        }
        switch (loadState.getState()) {
            case LoadState.PRE_LOAD:
                onPreLoad(loadState.getId());
                break;
            case LoadState.LOADING:
                onLoading(loadState.getId());
                break;
            case LoadState.FINISHED:
                onLoadFinish(loadState.getId());
                break;
        }
    }

    protected void onPreLoad(int id) {

    }

    protected void onLoading(int id) {

    }


    protected void onLoadFinish(int id) {

    }
}
